import React, { useState, useRef ,useEffect} from "react";

// Services
import AuthService from "../../services/auth.service.js";
import companiesService from "../../services/companies.service.js";
import userService from "../../services/user.service.js";
// Components
import { Link } from "react-router-dom";
import { Redirect } from "react-router-dom";
import {
  Button,
  Card,
  CardBody,
  Form,
  FormGroup,
  Col,
  Input,
  Alert,
} from "reactstrap";
import {  Check, X } from "react-feather";
import { Popover } from 'antd';

// Constants
const colors = ["danger"];

/*
* This is the company login / signup page
*
* This page will need to change depending on the user (Company) email address
* each company logo should be displayed with their primary & secondary colours
*
* TODO: Implement & connect to production
* TODO: Needs to be Tested
* */

const CompanyLoginPanel = (props) => {
  const [state, setstate] = useState("");
  const formCompany = useRef();

  const [partnerEmailLogin, setpartnerEmailLogin] = useState("");
  const [partnerPasswordLogin, setpartnerPasswordLogin] = useState("");

  const [messageCompany, setMessageCompany] = useState("");
  const [messageCompanySignup, setMessageCompanySignup] = useState("");
  const [visible1, setVisible1] = useState(true);
  const [visible2, setVisible2] = useState(true);
  const [loading, setLoading] = useState(false);
  const [companyUserEmail, setCompanyUserEmail] = useState("");
  const [companymessage, setcompanymessage] = useState("");
  const [visible, setVisible] = useState(false);
  const onDismiss = () => setVisible(false);
  const onDismiss1 = () => setVisible1(false);
  const onDismiss2 = () => setVisible2(false);
  const [visible3, setVisible3] = useState(false);
    const onDismiss3 = () => setVisible3(false);

  const onChangepartnerEmailLogin = (e) => {
    const username = e.target.value;
    setpartnerEmailLogin(username);
  };
  const onChangeCompanyUserEmail = (e) => {
    setCompanyUserEmail(e.target.value);
};

  const onChangepartnerPasswordLogin = (e) => {
    const password = e.target.value;
    setpartnerPasswordLogin(password);
  };
  
  const formUserSignup = useRef();



  const [passwordSignup, setPasswordSignup] = useState("");
  const [emailSignup, setEmailSignup] = useState("");

  const [firstNameSignup, setFirstNameSignup] = useState("");
  const [lastNameSignup, setLastNameSignup] = useState("");
  const [jobRoles, setJobRoles] = useState("");
  const [currentJobRole, setCurrentJobRole] = useState(0);
  const [passwordscore, setPasswordscore] = useState();

    //password rule
    const [PasspasswordRule1, setPasspasswordRule1] = useState(false);
    const [PasspasswordRule2, setPasspasswordRule2] = useState(false);
    const [PasspasswordRule3, setPasspasswordRule3] = useState(false);
    const [PasspasswordRule4, setPasspasswordRule4] = useState(false);

  const onChangePasswordSignup = (e) => {
    let passwordRule1 = /.{8,}/;
    let passwordRule2 = /[A-Z]/;
    let passwordRule3 = /[a-z]/;
    let passwordRule4 = /\d/;
    const password = e.target.value;
    if(passwordRule1.test(password)){
        setPasspasswordRule1(true)
    }else{
        setPasspasswordRule1(false)
    }
    if(passwordRule2.test(password)){
        setPasspasswordRule2(true)
    }else{
        setPasspasswordRule2(false)
    }
    if(passwordRule3.test(password)){
        setPasspasswordRule3(true)
    }else{
        setPasspasswordRule3(false)
    }
    if(passwordRule4.test(password)){
        setPasspasswordRule4(true)
    }else{
        setPasspasswordRule4(false)
    }
    setPasswordSignup(password);
  };

  const onChangeFirstName = (e) => {
      const firstName = e.target.value;
      setFirstNameSignup(firstName);
  };

  const onChangeLastName = (e) => {
      const lastName = e.target.value;
      setLastNameSignup(lastName);
  };

  const onChangeEmailSignup = (e) => {
      const email = e.target.value;
      setEmailSignup(email);
  };
  const onChangeJobRole = (e) => {
      const jobRole = e.target.value;
      setCurrentJobRole(jobRole);
  };

  const user = AuthService.getCurrentUser();
  var currentCompany = AuthService.getCurrentCompany();

  //if  user is logged in take to the user dashboard
  if (user) {
    props.history.push("/dashboard/default");
    window.location.reload();
  }
   // Fetch job roles from API & populate dropdown
   useEffect(() => {
        if (jobRoles.length === 0) {
            userService.GetJobRoles().then((response) => {
                if (response !== null) {
                    setJobRoles(response);
                }
            });
        }
    });
  //setting the state when the file is being uploaded (company logo)
  const onCompanyLogoChange = (event) => {
    // Update the state
    setstate({ file: event.target.files[0] });
  };

    const handleLogin = (e) => {
        e.preventDefault();
        setMessageCompany("");
        setLoading(true);
        if (partnerEmailLogin !== "" && partnerPasswordLogin !== "") {
            AuthService.loginUser(partnerEmailLogin, partnerPasswordLogin).then((response) => {
                if(response.password_reset_mandatory === "True"){
                    window.sessionStorage.setItem("password_reset_mandatory",partnerEmailLogin);
                    props.history.push("/auth/change-password");
                }else{
                    if (response.Message === "") {
                        setLoading(false);
                        props.history.push("/dashboard/default");
                        window.location.reload();
                    } else {
                        setLoading(false);
                        setVisible2(true)
                        setMessageCompany(response.Message);
                        props.history.push("/");
                    }
                }
            });
        } else {
            setLoading(false);
            setVisible2(true)
            setMessageCompany("Kindly fill all the fields");
        }
    };

  const handleSignupbyCompanyEmail = (e) =>{
    e.preventDefault();
        setcompanymessage("");
        if(companyUserEmail === ''){
            setVisible3(true)
            setcompanymessage('Please enter the email address.')
        }else{
            let reg = /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/
            if(!reg.test(companyUserEmail)){
                setVisible3(true)
                setcompanymessage('Invalid email address. Please try again.')
            }else{
                companiesService.GetCompanyPageUrl(companyUserEmail).then((response) => {
                    console.log(response);
                    if(response===null){
                        setVisible(true)
                    }else{
                        props.history.push(`/${response.company_page_url}/login`);
                        window.location.reload();
                    }
                })
            }
        }
    }
    const handleSignup = (e) => {
        e.preventDefault();
        setMessageCompanySignup("");
    
        if (
            passwordSignup !== "" &&
            firstNameSignup !== "" &&
            lastNameSignup !== "" &&
            emailSignup !== "" &&
            currentJobRole !== 0
        ) {
            if(!PasspasswordRule1 || !PasspasswordRule2 || !PasspasswordRule3|| !PasspasswordRule4){
                setVisible1(true)
                setMessageCompanySignup(
                    "Password is too weak. You must use a stronger password to continue."
                );
            }else{
                AuthService.registerUser(
                    firstNameSignup,
                    lastNameSignup,
                    emailSignup,
                    passwordSignup,
                    currentJobRole
                ).then((response) => {
                    if (response.data.Status === "Success") {
                        props.history.push("/thankyou");
                        window.location.reload();
                    } else {
                        setVisible1(true)
                        setMessageCompanySignup(response.data.Message);
                        props.history.push("/");
                    }
                });
            }
        } else {
            setVisible1(true)
            setMessageCompanySignup(
                "All the fields are required, kindly fill all the fields"
            );
        }
      };
  if (currentCompany === null) {
    return (
      <React.Fragment>
        <Col sm="5" md="8" lg="6" className="mx-auto p-0">
          <Card className="h-100 shadow-lg">
                <div className="signup-card">
                    <CardBody>
                        <div className="mt-5 ml-7 mr-7 pt-4 pl-4 pr-4 ">
                            <div className="text-center">
                                <h2 className="h2-black-heading mb-4">Sign up</h2>
                            </div>
                            <Form onSubmit={handleSignup} ref={formUserSignup}>
                                <FormGroup>
                                    <Input
                                        bsSize="lg"
                                        type="text"
                                        name="firstname"
                                        placeholder="First name"
                                        value={firstNameSignup}
                                        onChange={onChangeFirstName}
                                    />
                                </FormGroup>
                                <FormGroup>
                                    <Input
                                        bsSize="lg"
                                        type="text"
                                        name="lastname"
                                        placeholder="Last name"
                                        value={lastNameSignup}
                                        onChange={onChangeLastName}
                                    />
                                </FormGroup>
                                <FormGroup>
                                    <select
                                        className="custom-select"
                                        value={currentJobRole}
                                        onChange={onChangeJobRole}
                                    >
                                        <option key={0} value={0} disabled>
                                            Job Role
                                        </option>
                                        {jobRoles &&
                                        jobRoles.length > 0 &&
                                        jobRoles.map((schema) => {
                                            return (
                                                <option key={schema.id} value={schema.id}>
                                                    {schema.name}
                                                </option>
                                            );
                                        })}
                                    </select>
                                </FormGroup>
                                <FormGroup>
                                    <Input
                                        bsSize="lg"
                                        type="email"
                                        name="email"
                                        placeholder="Email"
                                        value={emailSignup}
                                        onChange={onChangeEmailSignup}
                                    />
                                </FormGroup>

                                <FormGroup>
                                    <Popover
                                        content={
                                            <div>
                                                <p>{PasspasswordRule1? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}At least 8 characters long.</p>
                                                <p>{PasspasswordRule2? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}Have at least one uppercase letter.</p>
                                                <p>{PasspasswordRule3? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}Have at least one lowercase letter.</p>
                                                <p>{PasspasswordRule4? <Check size={18} color="#22db62"/>:<X size={18} color="#eb1414"/>}Have at least one number.</p>
                                            </div>}
                                        placement="right"
                                        title={
                                            <span>
                                                Password requirements:
                                            </span>
                                        }
                                        trigger="focus">
                                        <Input
                                            type="password"
                                            bsSize="lg"
                                            placeholder="Password"
                                            name="password"
                                            // maxLength={10}
                                            value={passwordSignup}
                                            onChange={onChangePasswordSignup}
                                            onFocus={onChangePasswordSignup}
                                        />
                                    </Popover>                          
                                </FormGroup>
                                {/* <Link to="/thankyou"> */}
                                <button className="btn btn-primary ml-auto mr-0 d-block font-weight-bold">
                                    Signup
                                </button>
                                {/* </Link> */}
                                <div className={"mt-3"}>
                                    {messageCompanySignup && (
                                    <Alert color={colors} isOpen={visible1} toggle={onDismiss1}> 
                                        <div className="alert-message"  style={{padding:'0.95rem 1.2rem'}}>
                                        <strong>{messageCompanySignup}</strong>
                                        </div>
                                    </Alert>
                                    )}
                                </div>
                            </Form>
                        </div>
                    </CardBody>
                </div>
                <hr className={"mx-auto"} style={{width:'55%'}}/>
                    <div className="ml-5 mr-4 mb-4">
                    <div className="text-center">
                        <p className="font-weight-bold">
                            Does your organization want to sign up <br/>
                            to the SkillsGap Analysis platform?
                        </p>
                    </div>
                    <div className="text-center">
                        <button className="btn btn-primary font-weight-bold">
                            <Link to="/auth/interest" style={{color: "#ffffff"}}>Register Your Interest</Link>
                        </button>
                    </div>
            </div>
          </Card>
        </Col>

        <Col sm="5" md="8" lg="6" className="mx-auto p-0">
          <Card className="h-100 shadow-lg bg-primary">
            <div className="othercard">
              <CardBody>
                <div className="mt-5 ml-7 mr-7  p-4" style={{marginBottom:"11.5rem"}}>
                  <div className="text-center">
                    <h2 className="h2-heading mb-4 text-white">Login</h2>
                  </div>
                  <Form onSubmit={handleLogin} ref={formCompany}>
                    <FormGroup>
                      <Input
                        bsSize="lg"
                        type="email"
                        name="email"
                        placeholder="Email"
                        onChange={onChangepartnerEmailLogin}
                      />
                    </FormGroup>
                    <FormGroup>
                      <Input
                        bsSize="lg"
                        type="password"
                        name="password"
                        placeholder="Password"
                        onChange={onChangepartnerPasswordLogin}
                      />
                    </FormGroup>
                    <div className="signin-div">
                      {/* <Link to="/dashboard/default"> */}
                      <button className="btn btn-outline-primary text-white border-white d-block ml-auto mr-0  font-weight-bold" disabled={loading}>
                          {loading && (<span className="spinner-border spinner-border-sm"></span>)}
                          <span>Login</span>
                      </button>
                      {/* <Button className="btnBlue">login</Button> */}
                      {/* </Link> */}
                    </div>
                    <div className="forgot-div">
                      <small>
                        <Link className="btn btn-link text-white" style={{color: 'white'}} to="/auth/reset-password">
                          Forgot password?
                        </Link>
                      </small>
                    </div>
                  </Form>
                  <div>
                    {messageCompany && (
                      <Alert color={colors} isOpen={visible2} toggle={onDismiss2}>
                        <div className="alert-message"  style={{padding:'0.95rem 1.2rem'}}>
                          <strong>{messageCompany}</strong>
                        </div>
                      </Alert>
                    )}
                  </div>
                </div>
                <hr className="border-white mx-auto" style={{width:'55%'}}/>      
                <div className="company-login-card">
                    <div className="ml-4 mr-4">
                        <div className="text-center">
                        <div className="mb-4 text-white">
                            Login to Company
                        </div>
                        </div>
                        <Form className="col-8 mx-auto">
                            <FormGroup>
                                <Input
                                    bsSize="lg"
                                    type="email"
                                    placeholder="Email Address"
                                    value={companyUserEmail}
                                    onChange={onChangeCompanyUserEmail}
                                />
                            </FormGroup>
                            <div className="signin-div">
                                <button className="btn btn-outline-primary border-white ml-auto mr-0 d-block font-weight-bold text-white" onClick={handleSignupbyCompanyEmail}>
                                    Login
                                </button>
                            </div>
                            <div className="alert-box-custom mt-3">
                                {visible && <Alert color="danger" isOpen={visible} toggle={onDismiss}>
                                    <div className="alert-message"  style={{padding:'0.95rem 1.4rem'}}>
                                        <strong>
                                        The company does not exist in the system. If you have already received a welcome email from us please contact{' '}
                                        <a
                                        className="alert-link"
                                        href="https://skillsgapanalysis.com/contact"
                                        rel="noreferrer"
                                        target="_blank"
                                        style={{color: '#ffffff',textDecoration: 'revert'}}
                                        >
                                        customer support
                                        </a>
                                        . If you are a company interested in the platform please click on the Register Interest button.
                                        </strong>
                                    </div>
                                </Alert>}
                                {companymessage && (
                                        <Alert color="danger" isOpen={visible3} toggle={onDismiss3}>
                                            <div className="alert-message"  style={{padding:'0.95rem 1.2rem'}}>
                                                <strong>{companymessage}</strong>
                                            </div>
                                        </Alert>
                                    )
                                }
                            </div>
                        </Form>
                    </div>
                </div>
              </CardBody>
            </div>
          </Card>
        </Col>
      </React.Fragment>
    );
  } else {
    return (
      <div>
        <Redirect to="/dashboard/default" />
      </div>
    );
  }
};
export default CompanyLoginPanel;
